import React from 'react';
import { connect } from 'react-redux';
import { ListView } from 'ywen-mobile-ui';
import Immutable from 'immutable';
import BaseComponent from '../../components/common/baseComponent.js';
import Button from '../../components/common/button';
import ActionSheet from '../../components/common/actionSheet';
import { is, not } from '../../utils/validator';
import toast from '../../utils/toast';
import Loading from '../../components/common/loading';

@connect(({ invoice, loading }) => {
  const list = invoice.get('orderList');
  const selectedList = list.reduce((result, item) => result.concat(item.get('list').filter(refuel => refuel.get('selected'))), Immutable.List());
  const money = selectedList.reduce((total, refuel) => total + refuel.get('invoiceAmount'), 0);
  const invoiceInfo = invoice.get('invoiceInfoList').find(info => info.get('selected'));
  const openType = invoice.get('openType'); // 1个人， 2企业
  const userName = invoice.get('userName');
  const email = invoice.get('email');
  const btnEnabled = is('email', email) && openType && (openType === 1 ? !!userName : !!invoiceInfo);
  return {
    ready: invoice.getIn(['permission', 'ready']),
    enabled: invoice.getIn(['permission', 'enabled']),
    list,
    selectedList,
    money,
    invoiceInfo,
    showOrder: invoice.get('showOrder'),
    openType,
    userName,
    email,
    btnEnabled,
    busy: ['invoice/invoice'].some(action => loading.effects[action]),
    permission: invoice.get('permission'),
  };
})
class Invoice extends BaseComponent {
  componentDidMount() {
    this.requestData();
    if (this.props.permission.get('enabled') === false) {
      this.props.history.replace('invoiceBlocked');
    }

    const { init } = this.props.location.state || {};
    if (init) {
      this.props.dispatch({
        type: 'inovice/initData',
      });
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.permission !== this.props.permission && nextProps.permission.get('enabled') === false) {
      this.props.history.replace('invoiceBlocked');
    }
  }

  requestData = () => {
    this.props.dispatch({
      type: 'invoice/fetchOrderListIfNeeded',
    });
    this.props.dispatch({
      type: 'invoice/fetchInfoListIfNeeded',
      payload: { openType: 2 },
    });
    this.props.dispatch({
      type: 'invoice/fetchInvoiceStatus',
    });
  }

  showOrder = (showOrder) => {
    this.props.dispatch({
      type: 'invoice/showOrder',
      payload: showOrder,
    });
  }

  selectOrder = (index, subIndex) => {
    this.props.dispatch({
      type: 'invoice/selectOrder',
      payload: { index, subIndex },
    });
  }

  selectOpenType(openType) {
    this.setState({ openType });
    this.props.dispatch({
      type: 'invoice/openTypeChanged',
      payload: openType,
    });
    this.actionSheet.close();
  }

  showTypeSelector = () => {
    this.actionSheet.show({
      title: null,
      options: [
        {
          title: '个人普票',
          action: () => this.selectOpenType(1),
        },
        {
          title: '企业普票',
          action: () => this.selectOpenType(2),
        },
      ],
    });
  }

  userNameChanged = (e) => {
    this.props.dispatch({
      type: 'invoice/userNameChanged',
      payload: e.target.value,
    });
  }

  emailChanged = (e) => {
    this.props.dispatch({
      type: 'invoice/emailChanged',
      payload: e.target.value,
    });
  }

  goInvoiceInfo = (select = false) => {
    this.props.history.push({
      pathname: 'invoiceInfoList',
      state: { select },
    });
  }

  goInvoiceList = () => {
    this.props.history.push('invoiceList');
  }

  doInvoice = () => {
    const { openType, userName, selectedList, invoiceInfo, email } = this.props;
    if (selectedList.size === 0) {
      toast('请选择开票订单');
    } else if (!openType) {
      toast('请选择开票类型');
    } else if (openType === 1 && !userName) {
      toast('请填写个人名称');
    } else if (openType === 2 && !invoiceInfo) {
      toast('请选择开票信息');
    } else if (not('email', email)) {
      toast('请填写正确的邮箱地址');
    } else {
      this.props.dispatch({
        type: 'invoice/invoice',
        payload: {
          email,
          openType,
          tragetName: userName,
          invoiceInfoId: invoiceInfo ? invoiceInfo.get('infoId') : null,
          orderNoList: selectedList.map(refuel => refuel.get('orderNo')).toJS(),
        },
      });
    }
  }

  renderOrder = () => {
    const { list, selectedList } = this.props;

    const groups = list.map((group, index) => {
      const cells = group.get('list').map((refuel, subIndex) => {
        return (
          <div className="cell-wrapper" onClick={() => this.selectOrder(index, subIndex)} key={subIndex}>
            <i className={`iconfont ${refuel.get('selected') ? 'icon-checked' : 'icon-unchecked'}`} />
            <div className="refuel-cell">
              <div className="cell-header">
                <div>{refuel.get('createTime')}</div>
                <i className="iconfont icon-arrow" />
              </div>
              <div className="cell-row">
                <div className="cell-title">订单编号</div>
                <div className="cell-text">{refuel.get('orderNo')}</div>
              </div>
              <div className="cell-row">
                <div className="cell-title">支付金额</div>
                <div className="cell-text">{refuel.get('payAmountYuan')}</div>
              </div>
              <div className="cell-row">
                <div className="cell-title">加油油站</div>
                <div className="cell-text">{refuel.get('stationName')}</div>
              </div>
            </div>
          </div>
        );
      });
      return (
        <div className="cell-group" key={index}>
          <div className="group-header">{group.get('title')}</div>
          <div className="group-body">
            {cells}
          </div>
        </div>
      );
    });

    let btn;
    if (list.size > 0) {
      btn = <Button title="去开票" className="invoice-btn" clickFunc={() => this.showOrder(false)} disabled={selectedList.size === 0} />;
    }

    return (
      <div className="refuel-list-base invoice-order-list">
        <ListView
          className="list"
          // loadMore={}
          hasMore={false}
          empty={this.renderEmpty('没有加油订单')}
          renderFooter={this.renderFooter}
        >
          {groups}
        </ListView>
        {btn}
      </div>
    );
  }

  renderContent = () => {
    const { money, invoiceInfo, openType, userName, email, btnEnabled, busy } = this.props;
    let typeText;
    let typeCls = 'text';
    let targetView;
    if (openType === 1) {
      typeText = '个人普票';
      targetView = (
        <div className="content-row">
          <div>个人名称</div>
          <input value={userName} onChange={this.userNameChanged} maxLength={30} placeholder="请输入个人名称" />
        </div>
      );
    } else if (openType === 2) {
      typeText = '企业普票';
      if (invoiceInfo) {
        targetView = (
          <div onClick={() => this.goInvoiceInfo(true)}>
            <div className="content-row" onClick={this.showTypeSelector}>
              <div>开票单位</div>
              <div className="text">{invoiceInfo.get('companyName')}</div>
              <i className="iconfont icon-arrow" />
            </div>
            <div className="content-row" onClick={this.showTypeSelector}>
              <div>纳税人识别号</div>
              <div className="text">{invoiceInfo.get('taxCode')}</div>
            </div>
            <div className="content-row" onClick={this.showTypeSelector}>
              <div>地址和电话</div>
              <div className="text">{invoiceInfo.get('companyAddress')}</div>
            </div>
            <div className="content-row" onClick={this.showTypeSelector}>
              <div>开户行和账户</div>
              <div className="text">{invoiceInfo.get('bankBranch')}</div>
            </div>
          </div>
        );
      } else {
        targetView = (
          <div className="content-row" onClick={() => this.goInvoiceInfo(true)}>
            <div>开票信息</div>
            <div className="text placeholder">请选择开票信息</div>
            <i className="iconfont icon-arrow" />
          </div>
        );
      }

    } else {
      typeCls = 'text placeholder';
      typeText = '请选择开具个人发票或企业发票';
    }
    return (
      <div className="content">
        <div className="info-view">
          <p>1. 可开票金额指您实际支付的金额（不含折扣等优惠金额）</p>
          <p>2. 可开票有效期为60天，请及时提交申请</p>
          <p>3. 取票方式暂时只支持电子发票</p>
          <p>4. 单张发票最高开票限额不超过1000元</p>
        </div>
        <div className="content-row">
          <div>开票金额</div>
          <p className="money">{(money / 100).toFixed(2)}<span className="unit">元</span></p>
          <div className="back-btn" onClick={() => this.showOrder(true)}>返回选择订单</div>
        </div>
        <div className="content-row top" onClick={this.showTypeSelector}>
          <div>开票类型</div>
          <div className={typeCls}>{typeText}</div>
          <i className="iconfont icon-arrow" />
        </div>
        {targetView}
        <div className="content-row top" onClick={this.showTypeSelector}>
          <div>取票方式</div>
          <div className="text">电子发票</div>
        </div>
        <div className="content-row">
          <div>收件邮箱</div>
          <input type="email" value={email} onChange={this.emailChanged} maxLength={30} placeholder="请输入收件邮箱" />
        </div>
        <Button title="确认开票" className="invoice-btn" clickFunc={this.doInvoice} disabled={!btnEnabled} loading={busy} />
        <ActionSheet ref={actionSheet => this.actionSheet = actionSheet} />
      </div>
    );
  }
  render() {
    const { showOrder, permission } = this.props;
    if (!permission.get('ready')) {
      return <Loading />;
    }
    return (
      <div className="invoice-base">
        <div className="header">
          <div onClick={() => this.goInvoiceInfo(false)}>开票信息管理</div>
          <div onClick={this.goInvoiceList}>开票记录</div>
        </div>
        {showOrder ? this.renderOrder() : this.renderContent()}
      </div>
    );
  }
}

export default Invoice;
